package com.acceptable.qucun.generic.filter;

import com.acceptable.qucun.generic.util.StringFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
@WebFilter(filterName = "RedisFilter")
public class RedisFilter implements Filter{
    @Autowired private StringRedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(request.getAttribute("data_map") == null){
            filterChain.doFilter(request, response);
            return;
        }

        Map<String, String> dataMap = (Map<String, String>) request.getAttribute("data_map");
        // 取redis数据 放入request
        String key = dataMap.get("redis_key");
//        System.out.println("redis_key " + key);
        if(!StringFormatUtil.isEmpty(key)){
            String value = redisTemplate.opsForValue().get(key);
            dataMap.put("redis_map", value);
//            System.out.println("redis_map: " + value);
        }
        request.setAttribute("data_map", dataMap);
        filterChain.doFilter(request, response);
    }
}
